import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;

/**
 * Creater with IntelliJ IDEA.
 * Description:
 * User: 86152
 * Dae: 2022-08-01
 * Time: 20:54
 */
class Count {
    int num=0;
}
public class demo5 {
    public static void main(String[] args) throws InterruptedException {
        Count count = new Count();
        CountDownLatch count1 = new CountDownLatch(2);
        Semaphore semaphore = new Semaphore(1);
        Thread t1 = new Thread() {
            public void run() {
                try {
                    System.out.println("t1申请资源");
                    semaphore.acquire();
                    System.out.println("t1获取到资源");
                    for (int i=0;i<10000;i++) {
                        count.num++;
                    }
                    semaphore.release();
                    System.out.println("t1释放资源");
                    count1.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread t2 = new Thread() {
            public void run() {
                try {
                    System.out.println("t2申请资源");
                    semaphore.acquire();
                    System.out.println("t2获取到资源");
                    for (int i=0;i<10000;i++) {
                        count.num++;
                    }
                    semaphore.release();
                    System.out.println("t2释放资源");
                    count1.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        t1.start();
        t2.start();
        count1.await();
        System.out.println(count.num);
    }
}
